#include "filedeleter.h"
#include "source/logger.h"
#include <QDebug>
#include <QUrl>
#include <QFileInfo>
#include <QFileInfoList>

FileDeleter &FileDeleter::getInstance()
{
    static FileDeleter instance;
    return instance;
}

FileDeleter::FileDeleter(QObject *parent) : QObject(parent) {}

bool FileDeleter::deleteFile(const QString &filePath) {
    QProcess process;
    process.start("rm", QStringList() << filePath);
    process.waitForFinished();

    return process.exitStatus() == QProcess::NormalExit && process.exitCode() == 0;
}

QStringList FileDeleter::selectAllFiles(const QString &folderPath, const QStringList &filters) {
    QUrl url(folderPath);
    QString localPath = url.toLocalFile();  // 转换为本地文件系统路径
    LogDebug << "Folder path in C++: " << localPath;

    QDir dir(localPath);
    if (!dir.exists()) {
        LogDebug << "Folder does not exist: " << localPath;
        return QStringList();
    }

    dir.setNameFilters(filters);  // 根据传入的过滤器选择文件
    QStringList fileList = dir.entryList(QDir::Files);

    //LogDebug << "Files found: " << fileList;

    for (int i = 0; i < fileList.size(); ++i) {
        fileList[i] = dir.absoluteFilePath(fileList[i]);
    }

    LogDebug << "Files selected: " << fileList;
    return fileList;
}

QStringList FileDeleter::getFileTypes(const QString &folderPath) {
    QUrl url(folderPath);
    QString localPath = url.toLocalFile();  // 转换为本地文件系统路径
    LogDebug << "Folder path in C++: " << localPath;

    QDir dir(localPath);
    if (!dir.exists()) {
        LogDebug << "Folder does not exist: " << localPath;
        return QStringList();
    }

    QFileInfoList fileInfoList = dir.entryInfoList(QDir::Files);
    QSet<QString> fileTypes;

    foreach (const QFileInfo &fileInfo, fileInfoList) {
        QString suffix = fileInfo.suffix();
        if (!suffix.isEmpty()) {
            fileTypes.insert("*." + suffix);
        }
    }

    QStringList fileTypesList = QStringList(fileTypes.begin(), fileTypes.end());
    LogDebug << "File types found: " << fileTypesList;
    return fileTypesList;
}

bool FileDeleter::isDirectory(const QString &filePath) {
    QFileInfo fileInfo(filePath);
    return fileInfo.isDir();
}
